package com.yzy.soft.system.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.google.common.collect.Lists;
import com.yzy.soft.common.persistence.dao.MetadataDatabaseMapper;
import com.yzy.soft.common.persistence.dao.UrlJsonFieldsStructureMapper;
import com.yzy.soft.common.persistence.model.MetadataDatabase;
import com.yzy.soft.common.persistence.model.UrlJson;
import com.yzy.soft.config.HttpAPIService;
import com.yzy.soft.config.HttpResult;
import com.yzy.soft.core.base.controller.BaseController;
import com.yzy.soft.core.base.tips.ErrorTip;
import com.yzy.soft.core.base.tips.SuccessTip;
import com.yzy.soft.core.base.tips.Tip;
import com.yzy.soft.system.dto.TableDataDto;
import com.yzy.soft.system.freemarker.SynchronousJson;
import com.yzy.soft.system.util.JSONUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

//import com.yzy.soft.system.dto.MetadataDatabaseDto;

/**
 * 描述：测试控制层
 *
 * @author Yinzhiyuan
 * @date 2018-12-19 01:44:11
 */
@Api(value = "测试控制层")
@RestController
@RequestMapping("/urljson")
public class UrlJsonController extends BaseController {

    //@Autowired
    //private IMetadataDatabaseService metadataDatabaseService;

    @Autowired
    private MetadataDatabaseMapper metadataDatabaseMapper;

    @Autowired
    private SynchronousJson synchronousJson;

    @Autowired
    private UrlJsonFieldsStructureMapper urlJsonFieldsStructureMapper;
    @Autowired
    private HttpAPIService httpAPIService;

    /**
     * 描述：查询 测试列表
     */
    @ApiOperation(value = "查询测试")
    @GetMapping(value = "/page/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public TableDataDto getAll(@RequestParam(name = "page", defaultValue = "1", required = true) int page, @RequestParam(name = "limit", defaultValue = "10", required = true) int pageSize) throws Exception {

        Wrapper<MetadataDatabase> metadataDatabase = new EntityWrapper<MetadataDatabase>();
        page = (page - 1) * pageSize;
        pageSize = page + pageSize;
        List<MetadataDatabase> result = metadataDatabaseMapper.selectPage(new RowBounds(page, pageSize), metadataDatabase);
        TableDataDto tableDataDto = new TableDataDto();
        tableDataDto.setCode("00");
        tableDataDto.setMsg("000");
        tableDataDto.setCount(metadataDatabaseMapper.selectCount(metadataDatabase));
        tableDataDto.setData(result);
        return tableDataDto;
    }

    /**
     * 描述：根据Id 查询 测试
     *
     * @param id 测试id
     */
    @ApiOperation(value = "查询测试")
    @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public MetadataDatabase findById(@PathVariable("id") String id) throws Exception {
        return metadataDatabaseMapper.selectById(id);
    }

    /**
     * 描述:创建测试
     *
     * @param metadataDatabaseDTO 测试DTO
     */
    @ApiOperation(value = "创建测试")
    @PostMapping("")
    public Tip create(@ModelAttribute MetadataDatabase metadataDatabase) {
        metadataDatabase.setCreatetime(new Date());
        metadataDatabase.setLastupdatetime(new Date());
        Integer result = metadataDatabaseMapper.insert(metadataDatabase);
        return SUCCESS_TIP;
    }

    /**
     * 描述：删除测试
     *
     * @param id 测试id
     */
    @ApiOperation(value = "删除测试")
    @DeleteMapping("/{id}")
    public Tip delete(@RequestParam(name = "ids[]", required = false) String[] metadataDatabase, @PathVariable(name = "id", required = false) String id) {
        //Collections.<String>
        if (StringUtils.isNotBlank(id)) {
            Integer result = metadataDatabaseMapper.deleteById(id);
        } else if (metadataDatabase.length != 0) {
            Integer result = metadataDatabaseMapper.deleteBatchIds(Lists.newArrayList(metadataDatabase));
        }
        return SUCCESS_TIP;
    }

    @ApiOperation(value = "批量删除测试")
    @DeleteMapping("/")
    public Tip delete1(@RequestParam(name = "ids[]", required = false) String[] metadataDatabase) {
        if (metadataDatabase.length != 0) {
            Integer result = metadataDatabaseMapper.deleteBatchIds(Lists.newArrayList(metadataDatabase));
        }
        return SUCCESS_TIP;
    }


    /**
     * 描述：更新测试
     *
     * @param id 测试id
     */
    @ApiOperation(value = "更新测试")
    @PutMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Tip updateMetadataDatabase(@ModelAttribute MetadataDatabase metadataDatabase) throws Exception {
        metadataDatabase.setLastupdatetime(new Date());
        Integer result = metadataDatabaseMapper.updateById(metadataDatabase);
        return SUCCESS_TIP;
    }

    @GetMapping("/by")
    public TableDataDto getCadtion(@ModelAttribute MetadataDatabase metadataDatabase) {
        Wrapper<MetadataDatabase> wrapper = new EntityWrapper<MetadataDatabase>();
        wrapper.where("company_id={0}", metadataDatabase.getCompanyId());
        List<MetadataDatabase> result = metadataDatabaseMapper.selectList(wrapper);
        TableDataDto tableDataDto = new TableDataDto();
        tableDataDto.setCode("00");
        tableDataDto.setMsg("000");
        tableDataDto.setCount(result.size());
        tableDataDto.setData(result);
        return tableDataDto;
    }

    @PutMapping("/status/{id}")
    public Tip status(@PathVariable("id") Integer id) {
        Integer result = metadataDatabaseMapper.status(id);
        if (null == result) {
            return new ErrorTip(500, "s");
        }
        return SUCCESS_TIP;
    }

    @GetMapping("/metadataDatabaseId/{metadataDatabaseId}")
    public TableDataDto getbyAccountId(@PathVariable(name = "metadataDatabaseId") String metadataDatabaseId, @RequestParam(name = "page", defaultValue = "1", required = true) int page, @RequestParam(name = "limit", defaultValue = "10", required = true) int pageSize) {
        Wrapper<MetadataDatabase> metadataDatabaseWrapper = new EntityWrapper<>();
        metadataDatabaseWrapper.where("accountid={0}", metadataDatabaseId);
        page = (page - 1) * pageSize;
        pageSize = page + pageSize;
        List<MetadataDatabase> result = metadataDatabaseMapper.selectPage(new RowBounds(page, pageSize), metadataDatabaseWrapper);
        TableDataDto tableDataDto = new TableDataDto();
        tableDataDto.setCode("00");
        tableDataDto.setMsg("000");
        tableDataDto.setCount(metadataDatabaseMapper.selectCount(metadataDatabaseWrapper));
        tableDataDto.setData(result);
        return tableDataDto;
    }

    @ApiOperation("批量将费用归档设置成弃用状态")
    @PostMapping("/batchNuUse")
    public Tip batchNuUse(@RequestParam(name = "ids[]", required = false) Integer[] metadataDatabase) {
        if (metadataDatabase.length != 0) {
            Integer result = metadataDatabaseMapper.batchNuUseIds(Lists.newArrayList(metadataDatabase));
        }
        return SUCCESS_TIP;
    }

    @ApiOperation("批量将费用归档设置成可用状态")
    @PostMapping("/batchUse")
    public Tip batchUse(@RequestParam(name = "ids[]", required = false) Integer[] metadataDatabase) {
        if (metadataDatabase.length != 0) {
            Integer result = metadataDatabaseMapper.batchUseIds(Lists.newArrayList(metadataDatabase));
        }
        return SUCCESS_TIP;
    }

    @ApiOperation("同步数据库信息")
    @GetMapping("/synchronous/{id}")
    public Tip synchronous(@PathVariable("id") Integer id) {
//        SynchronousMetadata synchronousMetadata=new SynchronousMetadata();
//        synchronousMetadata.synchronousMetadataDatabase(id);
//        if(null==result){
//            return new ErrorTip(500,"s");
//        }
        return SUCCESS_TIP;
    }

    @ApiOperation("同步数据库信息")
    @GetMapping("/synchronous")
    public Tip synchronousAll() {
//        SynchronousMetadata synchronousMetadata=new SynchronousMetadata();
//        synchronousMetadata.synchronousMetadataDatabase();
//        if(null==result){
//            return new ErrorTip(500,"s");
//        }
        return SUCCESS_TIP;
    }


    @ApiOperation("json连接测试")
    @PostMapping("/connectTest")
    public Tip connectTest(@ModelAttribute UrlJson urlJson) {
        try {
            httpAPIService.connectTest(urlJson);
        } catch (Exception e) {
            e.printStackTrace();
            new ErrorTip(500, "s");
        }
        return SUCCESS_TIP;
    }

    @ApiOperation("json结构存储")
    @PostMapping("/structuralStorage")
    public Tip jsonStrStroger(@ModelAttribute UrlJson urlJson) throws Exception {

        HttpResult httpResult = httpAPIService.connectTest(urlJson);

        String ss = "{\"title\":\"新增的任务的表单信息\",\"type\":\"object\",\"properties\":{\"finishTime\":{\"type\":\"number\",\"title\":\"任务结束时间例如：1450708950086\"},\"contactEmail\":{\"type\":\"string\",\"title\":\"联系人邮箱\"},\"sexType\":{\"type\":\"string\",\"title\":\"招聘性别要求,FEMALE:女，MALE：男，UNKWON：男女不限\"},\"enrollEndTime\":{\"type\":\"number\",\"title\":\"报名截止时间例如：1450708950086\"},\"description\":{\"type\":\"string\",\"title\":\"备注\"},\"weekday\":{\"type\":\"string\",\"title\":\"工作日期\"},\"title\":{\"type\":\"string\",\"title\":\"任务标题\"},\"startTime\":{\"type\":\"number\",\"title\":\"任务开始时间,例如：1450708950086\"},\"contactTelephone\":{\"type\":\"string\",\"title\":\"联系人电话\"},\"timeDescription\":{\"type\":\"string\",\"title\":\"工作时间描述\"},\"paymentType\":{\"type\":\"string\",\"title\":\"支付类型 0：线上支付，1：线下支付\"},\"addressList\":{\"items\":{\"properties\":{\"latitude\":{\"type\":\"string\",\"title\":\"纬度\"},\"cityName\":{\"type\":\"string\",\"title\":\"城市名称\"},\"areaName\":{\"type\":\"string\",\"title\":\"区域名称\"},\"longitude\":{\"type\":\"string\",\"title\":\"经度\"},\"address\":{\"type\":\"string\",\"title\":\"t工作地点\"}},\"type\":\"object\",\"description\":\"任务地址\"},\"type\":\"array\",\"title\":\"地址列表\"},\"balanceUnit\":{\"type\":\"string\",\"title\":\"兼职金额单位；例如：元/小时，元/天等\"},\"contactName\":{\"type\":\"string\",\"title\":\"联系人姓名\"},\"content\":{\"type\":\"string\",\"title\":\"工作内容\"},\"balance\":{\"type\":\"number\",\"title\":\"兼职金额\"},\"headcount\":{\"type\":\"integer\",\"title\":\"招聘人数\"},\"typeDesc\":{\"type\":\"string\",\"title\":\"任务类型描述: 只有在任务类型为其他时有效\"},\"type\":{\"type\":\"string\",\"title\":\"任务类型；例如：传单派发，服务员等\"},\"balanceType\":{\"type\":\"integer\",\"title\":\"结算类型；例如：完工结，日结等\"},\"array\":{\"arrayTest\":[\"integer\",\"integer\"]}}}";


        String result = httpResult.getBody();
        if (null == result) {
            throw new Exception("请求响应无效");
        }
        //效验是否为合法的json格式数据
        String d=JSONUtil.FastJsonFormatter(result);



//        for (int i = 0; i < res.size(); i++) {
//            UrlJsonFieldsStructure urlJsonFieldsStructure1 = res.get(i);
//            System.out.println(urlJsonFieldsStructure1.getFieldName() + " " + urlJsonFieldsStructure1.getFieldType() + " " + urlJsonFieldsStructure1.getLevel());
//        }
        synchronousJson.fieldsStructuralStorage(d);

//        if (synchronousMetadata.connectTest(metadataDatabase)) {
//            return SUCCESS_TIP;
//        }
//        return new ErrorTip(500, "s");
        return new SuccessTip(200,"请求响应成功，响应结构为："+d);
    }
}